package com.learn.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * NIO客户端
 *
 * @author wangxing
 * @version 2020/7/29 16:49 Administrator
 */
public class NIOClient {
    //    通道管理器
    private Selector selector;

    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(3, 3, 1000, TimeUnit.SECONDS,
                new ArrayBlockingQueue(10));
        poolExecutor.execute(() -> {
            NIOClient client = new NIOClient();
            try {
                client.initClient("127.0.0.1", NIOServer.PORT);
                client.select();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    public void initClient(String ip, int port) throws IOException {
//        获得一个Socket通道
        SocketChannel channel = SocketChannel.open();
//        设置通道为非阻塞
        channel.configureBlocking(false);
//        获得一个通道管理器
        this.selector = Selector.open();
//        客户端连接服务器,其方法执行并没有实现连接,需要在listen方法中调用channel.finishConnect();才能完成连接
        channel.connect(new InetSocketAddress("127.0.0.1", 9000));
//        将通道管理器和该通道绑定,并为通道注册SelectionKey.OP_CONNECT事件(连接事件)
        channel.register(this.selector, SelectionKey.OP_CONNECT);
    }

    /**
     * 对选择器中数据进行判定
     *
     * @throws IOException
     */
    public void select() throws IOException {
//        轮询访问selector(选择器/多路复用器)
        while (true) {
//            阻塞等待获取到返回信息
            this.selector.select();
            System.out.println(System.currentTimeMillis());
//            获取selector中选中的迭代器
            Iterator<SelectionKey> it = this.selector.selectedKeys().iterator();
            while (it.hasNext()) {
//                获取访问的key
                SelectionKey selectionKey = it.next();
//                删除已经获取的迭代器中数据
                it.remove();
                handle(selectionKey);
            }

        }
    }

    /**
     * 处理事件
     *
     * @param selectionKey 选择器键
     * @throws IOException
     */
    private void handle(SelectionKey selectionKey) throws IOException {
        if (selectionKey.isConnectable()) {
//                如果获取到的事件是连接事件
            connect(selectionKey);
        } else if (selectionKey.isReadable()) {
//                获取到的是读取事件
            read(selectionKey);
        }
    }

    /**
     * 连接事件
     *
     * @param key
     */
    private void connect(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();
//        当前正在连接,则完成连接
        if (socketChannel.isConnectionPending()) {
//            完成连接
            socketChannel.finishConnect();
        }
//        设置为非阻塞连接
        socketChannel.configureBlocking(false);
//        设置要发送的消息
        ByteBuffer buffer = ByteBuffer.wrap("hello i am nio client".getBytes());
//        发送消息
        socketChannel.write(buffer);
//        注册读取事件到选择器中,等待有读取事件发生
        socketChannel.register(this.selector, SelectionKey.OP_READ);
    }

    /**
     * 读取事件
     *
     * @param key
     */
    private void read(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        int len = socketChannel.read(buffer);
        if (len != -1) {
            System.out.println("客户端收到消息:");
            System.out.println(new String(buffer.array(), 0, len));
            while ((len = socketChannel.read(buffer)) > 0) {
                System.out.println(new String(buffer.array(), 0, len));
            }
        }
        write(key);
    }

    private void write(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        Scanner scanner = new Scanner(System.in);
        String message = "";
        if (scanner.hasNext()) {
            message = scanner.nextLine();
        }
        scanner.close();
        ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
        socketChannel.write(buffer);
        key.interestOps(SelectionKey.OP_READ);
    }
}
